package com.example.demo.socket;
import java.awt.event.MouseEvent;
import com.example.demo.service.GomokuGameService;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class GameWebSocketHandler1 extends TextWebSocketHandler {
    private final GomokuGameService gameService = new GomokuGameService();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>(); // 存储客户端会话

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 生成唯一会话ID
        String sessionId = UUID.randomUUID().toString();
        sessions.put(sessionId, session);
        session.getAttributes().put("sessionId", sessionId);

        System.out.println("客户端已连接，会话ID: " + sessionId);
        sendState(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {       //接收数据的
        String input = message.getPayload();
//        log.info(input);
        String sessionId = (String) session.getAttributes().get("sessionId");

        if (sessionId == null) {
            session.close();
            return;
        }
        try {
            if ("RESET".equalsIgnoreCase(input)) {
                // 处理重置请求
                gameService.reset();
                broadcastState();
            } else {
                // 解析落子请求
                Map<String, Integer> move = objectMapper.readValue(input, Map.class);
                Integer row = move.get("row");
                Integer col = move.get("col");

                if (row != null && col != null) {
                    // 调用游戏服务处理落子
                    processMove(row, col);
                    broadcastState();
                }
            }
        } catch (Exception e) {
            System.err.println("处理客户端消息出错: " + e.getMessage());
            session.sendMessage(new TextMessage("ERROR: " + e.getMessage()));
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String sessionId = (String) session.getAttributes().get("sessionId");
        if (sessionId != null) {
            sessions.remove(sessionId);
            System.out.println("客户端已断开，会话ID: " + sessionId);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String sessionId = (String) session.getAttributes().get("sessionId");
        if (sessionId != null) {
            System.err.println("客户端传输错误，会话ID: " + sessionId + ": " + exception.getMessage());
            sessions.remove(sessionId);
        }
        if (session.isOpen()) {
            session.close();
        }
    }

    private void processMove(int row, int col) {
        // 调用游戏服务处理落子（假设GomokuGameService有公共方法）
        gameService.makeMove(row, col); // 需在GomokuGameService中添加此方法
    }

    private void sendState(WebSocketSession session) {
        try {
            String json = objectMapper.writeValueAsString(gameService.getState());
            session.sendMessage(new TextMessage(json));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void broadcastState() {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(gameService.getState());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        TextMessage message = new TextMessage(json);
        sessions.values().forEach(session -> {
            try {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}